import User from '../../sql/module/user/user';
import Material from '../../sql/module/factory/material';
import MaterialType from '../../sql/module/factory/material_type';
import { TypeValidator, MateriaValidator, UpdateMateriaValidator } from '../../validators/material';
import { InfoValidator, ListValidator } from '../../validators/public';
import auth from '../../middlewares/auth';
import { Success, NotFound, Fail } from '../../code/http-exception';
import { Op } from 'sequelize';

const router: Api = new Map()

User.hasMany(Material);
Material.belongsTo(User);
MaterialType.hasMany(Material);
Material.belongsTo(MaterialType);

//获取材料类型列表
router.set('/typeList', [auth('materialType'), async (ctx, next) => {
    const { rows, count } = await MaterialType.findAndCountAll()
    throw new Success({ list: rows, total: count })
}])

//获取材料类型列表
router.set('/types', [auth(['addMaterial', 'updateMaterial']), async (ctx, next) => {
    const materials = await MaterialType.findAll()
    throw new Success(materials)
}])

//添加材料类型
router.set('/addType', [auth('materialType'), async (ctx, next) => {
    const v = await new TypeValidator().validate(ctx)
    await MaterialType.create({
        name: v.get('body.name')
    })
    throw new Success()
}])

//删除材料类型
router.set('/delteType', [auth('materialType'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const type = await MaterialType.findOne({
        where: {
            id: v.get('query.id')
        }, include: Material
    })
    if (!type) { throw new NotFound() }
    if (type.dataValues.Materials.length) throw new Fail('存在相关材料，不可删除')
    await type.destroy()
    throw new Success()
}])

//材料列表
router.set('/materiaList', [auth('materiaList'), async (ctx, next) => {
    const v = await new ListValidator().validate(ctx)
    const UserId = ctx.auth.id
    const limit = v.get('query.limit')
    const page_index = v.get('query.page_index')
    const name = v.get('body.name')
    const MaterialTypeId = v.get('body.MaterialTypeId')
    const where: any = { UserId }
    const typeWhere: any = {}
    name && (where.name = {
        [Op.substring]: name
    })
    MaterialTypeId && (typeWhere.id = MaterialTypeId)
    const { rows, count } = await Material.findAndCountAll({
        where,
        include: { model: MaterialType, where: typeWhere, attributes: ['name'] },
        distinct: true,
        limit: limit * 1,
        offset: (page_index - 1) * limit,
        order: [['id', 'DESC']]
    })
    throw new Success({ list: rows, total: count })
}])

//添加材料
router.set('/addMaterial', [auth('addMaterial'), async (ctx, next) => {
    const v = await new MateriaValidator().validate(ctx)
    const UserId = ctx.auth.id
    await Material.create({
        UserId,
        name: v.get('body.name'),
        MaterialTypeId: v.get('body.MaterialTypeId'),
        address: v.get('body.address'),
        phone: v.get('body.phone'),
        img: v.get('body.fullUrl')
    })
    throw new Success()
}])

//获取材料详情
router.set('/materiaInfo', [auth('updateMaterial'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const id = v.get('query.id')
    const UserId = ctx.auth.id
    const material = await Material.findOne({
        where: { id, UserId }
    })
    throw new Success(material)
}])

//修改材料信息
router.set('/updateMateria', [auth('updateMaterial'), async (ctx, next) => {
    const v = await new UpdateMateriaValidator().validate(ctx)
    const id = v.get('query.id')
    const name = v.get('body.name')
    const phone = v.get('body.phone')
    const UserId = ctx.auth.id
    const material = await Material.findOne({ where: { id, UserId } })
    if (!material) throw new NotFound()
    await material.update({
        name, phone
    })
    throw new Success()
}])

//修改材料状态
router.set('/changeState', [auth('changeMaterialState'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const id = v.get('query.id')
    const material = await Material.findOne({
        where: { id, UserId }
    })
    if (!material) { throw new NotFound() }
    const state = !material.dataValues.state
    await material.update({
        state
    })
    throw new Success(state)
}])

//删除材料
router.set('/delete', [auth('deleteMaterial'), async (ctx, next) => {
    const v = await new InfoValidator().validate(ctx)
    const UserId = ctx.auth.id
    const id = v.get('query.id')
    const material = await Material.findOne({
        where: { id, UserId }
    })
    if (!material) { throw new NotFound() }
    await material.destroy()
    throw new Success()
}])

export { router }